package com.tony.business.controller;

import com.tony.domain.bo.JsonResult;
import com.tony.domain.exception.CustomException;
import com.tony.domain.enumerate.ISystemEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tony
 * @date 2020/3/1 10:39 下午
 */
@Api(tags = "获取枚举的")
@RequestMapping("/enums")
@RestController
public class EnumsController {

    @GetMapping("/{name}")
    @ApiOperation(value = "查询枚举", httpMethod = "GET")
    public JsonResult<Map<String, String>> selectEnumMap(@PathVariable("name") String name) throws ClassNotFoundException {
        char[] chars = name.toCharArray();
        if (chars[0] >= 'a' && chars[0] <= 'z') {
            chars[0] = (char) (chars[0] - 32);
        }
        String className = "com.tony.domain.enumerate." + String.valueOf(chars) + "Enum";
        Class<?> clazz = Class.forName(className);
        if (clazz.isInstance(ISystemEnum.class)) {
            throw new CustomException("不属于ISystemEnum子类");
        }
        Object[] enumConstants = clazz.getEnumConstants();
        return new JsonResult<>(getEnumMap((ISystemEnum[]) enumConstants));
    }

    /**
     * 把枚举数组转换为map
     *
     * @param systemEnums 枚举数组
     * @return map
     */
    private static Map<String, String> getEnumMap(final ISystemEnum[] systemEnums) {
        Map<String, String> map = new HashMap<>(systemEnums.length);
        for (ISystemEnum value : systemEnums) {
            map.put(value.getName(), value.getDesc());
        }
        return map;
    }


}
